#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include "contacts.pb.h"

const std::string contacts_file="./contacts.bin";

void PrintContacts(const contacts::Contacts &cons) {

  for(int i=0;i<cons.contacts_size();++i) {

    std::cout<<"-----------------联系人 "<<i+1<<"-----------------"<<std::endl;

    const contacts::PeopleInfo &people=cons.contacts(i);

    std::cout<<"联系人姓名: "<<people.name()<<std::endl;
    std::cout<<"联系人年龄: "<<people.age()<<std::endl;

    // 获取联系人号码
    for(int j=0;j<people.phone_size();++j) {

      const contacts::PeopleInfo_Phone phone=people.phone(j);

      std::cout<<"号码"<<j+1<<" : "<<phone.number();
      std::cout<<"   ( "<<phone.PhoneType_Name(phone.type())<<" )   "<<std::endl;
    }

    if (people.has_data() && people.data().Is<contacts::Address>()) {
            contacts::Address address;
            people.data().UnpackTo(&address);
            if (!address.home_address().empty()) {
                std::cout << "联系人家庭地址：" << address.home_address() << std::endl;
            }
            if (!address.unit_address().empty()) {
                std::cout << "联系人单位地址：" << address.unit_address() << std::endl;
            }
        }

  }
  
  std::cout<<std::endl;
}

int main() {

    // 打开文件
    std::fstream input(contacts_file,std::ios::in | std::ios::binary);
    if(!input.is_open()) {

      std::cerr<<" 打开 "<<contacts_file<<" 失败! "<<std::endl;

      exit(-1);
    }
    // 读取文件+反序列化
    contacts::Contacts cons;
    if(!cons.ParseFromIstream(&input)) {

      std::cerr<<" 反序列失败! "<<std::endl;

      exit(-2);
    }

    // 打印通讯录
    PrintContacts(cons);

    input.close();

    return 0;
}

/*

[yx@VM-12-12-centos ProtoBuf]$ protoc --decode=contacts.Contacts contacts.proto < contacts.bin 
contacts {
  name: "\345\274\240\344\270\211"
  age: 20
  phone {
    number: "1234567890"
  }
  phone {
    number: "0987654321"
  }
}

*/

/*
[yx@VM-12-12-centos ProtoBuf]$ hexdump -C contacts.bin 
00000000  0a 26 0a 06 e5 bc a0 e4  b8 89 10 14 1a 0c 0a 0a  |.&..............|
00000010  31 32 33 34 35 36 37 38  39 30 1a 0c 0a 0a 30 39  |1234567890....09|
00000020  38 37 36 35 34 33 32 31                           |87654321|
00000028
*/